package com.briup.es.web.controller;

import com.briup.es.config.auth.SecurityUserContext;
import com.briup.es.config.response.Result;
import com.briup.es.domain.bean.User;
import com.briup.es.domain.dto.UserLoginDTO;
import com.briup.es.domain.dto.UserDTO;
import com.briup.es.domain.dto.UserUpdatePasswordDTO;
import com.briup.es.service.UserService;
import com.briup.es.validate.Add;
import com.briup.es.validate.Update;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    // 在参数类型前添加@Valid注解，那么框架就会帮我们进行参数校验
    // @Valid 注解是jakarta.validation提供的注解，即Java的原生注解，能够实现基础的参数校验
    // @Validated 注解springframework.validation提供的注解，能够实现分组校验等功能
    @PostMapping("/register")
    public Result<?> register(@RequestBody @Validated(Add.class) UserDTO userRegisterDTO){
        userService.register(userRegisterDTO);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody @Valid UserLoginDTO loginDTO){
        Map<String,Object> map = userService.login(loginDTO);
        return Result.success(map);
    }

    @GetMapping("/getUserInfo")
    public Result<User> getUserInfo(){
        // 从请求认证上下文中 获取当前登录用户的对象
        User user = SecurityUserContext.currentUser();
        return Result.success(user);
    }

    @PutMapping("/updatePassword")
    public Result<?> updatePassword(@RequestBody @Valid UserUpdatePasswordDTO updatePasswordDTO){
        userService.updatePassword(updatePasswordDTO);
        return Result.success();
    }


    @PutMapping("/updateUser")
    public Result<?> updateUser(@RequestBody @Validated(Update.class) UserDTO userDTO){
        userService.updateUser(userDTO);
        return Result.success();
    }
}
